<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区-->
    <el-card class="box-card">
      <!--搜索与添加区-->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" clearable @clear="getUserList()" v-model="queryInfo.query" class="input-with-select">
            <el-button slot="append" @click="getUserList()" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!--表格区-->
    <el-table :data="userList" border stripe>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="create_time" label="时间"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="editFormUser(scope.row.id)"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-remove" @click="delUser(scope.row.id)"></el-button>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable=false>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="asignRoleDialog(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog()">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑用户对话框-->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="closeEditDialog()">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="角色分配" :visible.sync="assignRoleDialogVisible" width="50%" @close="closeAssignRoleDialog()">
      <el-table :data="roleList" border stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialogVisible = false">取 消</el-button>
        <el-button @click="assignRole()" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱验证规则
    var volidateEmail = (rule, value, callback) => {
      var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 自定义手机号验证规则
    var volidatePhone = (rule, value, callback) => {
      var regPhone = /^1[3456789]\d{9}$/
      if (regPhone.test(value)) {
        callback()
      }
      callback(new Error('请输入正确的手机号格式'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: volidateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: volidatePhone }
        ]
      },
      // 编辑
      editDialogVisible: false,
      editForm: {
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: volidateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: volidatePhone, trigger: 'blur' }
        ]
      },
      // 角色分配相关
      userid: '',
      assignRoleDialogVisible: false,
      roleList: []
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      // 请求用户数据 请求方式get 请求路径users 参数query pagenum pagesize
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        this.$message.error('用户列表获取失败')
      }
      // console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 状态切换改变
    async changeState (user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
      } else {
        this.$message.error('设置失败')
        user.mg_state = !user.mg_state
      }
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async (valid, obj) => {
        if (!valid) {
          return
        }
        let { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
          return
        }
        this.$message.success('添加用户成功')
        // 关闭对话框
        this.addDialogVisible = false
        // 刷新表格数据
        this.getUserList()
      })
    },
    // 监听每页数据条数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
      console.log(newSize)
    },
    // 监听当前页
    handleCurrentChange (newCurrentPage) {
      this.queryInfo.pagenum = newCurrentPage
      this.getUserList()
      console.log(newCurrentPage)
    },
    // 监听对话框关闭触发的函数
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击编辑出现对话框
    async editFormUser (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 关闭编辑对话框
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 保存编辑信息
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return// this.$message.error('信息保存失败')
        }
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) {
          return this.$message.error('信息保存失败')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 提示修改成功
        this.$message.success('修改信息成功')
        // 刷新表格
        this.getUserList()
      })
    },
    // 删除用户
    async delUser (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { return err })
      if (confirmRes !== 'confirm') {
        return this.$message.warning('取消了删除操作')
      }
      // 删除用户
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      // 提示删除成功
      this.$message.success('删除用户成功')
      // 刷新表格
      this.getUserList()
    },
    // 分配角色
    async asignRoleDialog (id) {
      // 查询所有的角色
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status === 200) {
        this.assignRoleDialogVisible = true
        this.roleList = res.data
        this.userid = id
      }
    },
    // 关闭分配角色对话框
    closeAssignRoleDialog () {
      this.assignRoleDialogVisible = false
    },
    // 分配角色功能
    assignRole () {
      // var userid = this.userid
    }
  }
}
</script>

<style lang="less" scoped>

</style>
